package com.sjgs.gis.utils;



import org.springframework.core.io.Resource;
import org.springframework.core.io.support.ResourceRegion;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRange;

import java.io.IOException;

import static java.lang.Long.max;
import static java.lang.Long.min;

public class RegionUtils {
    public static int byteLength = 1024;
    public static long CHUNK_SIZE_LOW = byteLength * 1024;
    public static long CHUNK_SIZE_MED = byteLength * 2048;
    public static long CHUNK_SIZE_HIGH = CHUNK_SIZE_LOW * 4;

    public static ResourceRegion getResourceRegion(Resource resource, HttpHeaders headers) {
        HttpRange range = headers.getRange().size() != 0 ? headers.getRange().get(0) : null;
        //VLC/3.0.10 LibVLC/3.0.10
        //String userAgent = headers.get("User-Agent").size() != 0 ? headers.get("User-Agent").get(0) : null;
        //Browser browser = UserAgent.parseUserAgentString(userAgent).getBrowser();
        //Version version = browser.getVersion(userAgent);
        long contentLength = 0;
        contentLength = lengthOf(resource);
        if (range != null) {
            long start = range.getRangeStart(contentLength);
            long end = range.getRangeEnd(contentLength);
            long resourceLength = end - start + 1;
            long count = 0;
            if (contentLength < CHUNK_SIZE_MED) {
                count = min(CHUNK_SIZE_MED, resourceLength);
            } else {
                count = max(CHUNK_SIZE_MED, resourceLength);
            }
            return new ResourceRegion(resource, start, count);
        } else {
            //FIXME 整文件下载算法资源分配待优化
            return new ResourceRegion(resource, 0, contentLength);
        }
    }

    public static long lengthOf(Resource resource) {
        long fileLength=0L;
        try {
            fileLength = resource.contentLength();
        } catch (IOException e) {
            ;
        }
        return fileLength;
    }

    public static long countOf(Long length, long chunk_size) {
        return length % chunk_size == 0 ? Math.floorDiv(length, chunk_size) : Math.floorDiv(length, chunk_size) + 1;
    }
}
